from flask import render_template, request, redirect, url_for, flash
from flask_login import login_required
from . import water
from .. import db
from ..models import Device, WaterQuality
from datetime import datetime
from sqlalchemy import and_

@water.route('/water')
@login_required
def water_index():
    # 获取查询参数
    search_device_id = request.args.get('device_id', '')
    search_name = request.args.get('name', '')
    search_location = request.args.get('location', '')
    
    # 构建查询条件
    query = Device.query.filter_by(device_type='sensor')
    if search_device_id:
        query = query.filter(Device.device_id.like(f'%{search_device_id}%'))
    if search_name:
        query = query.filter(Device.name.like(f'%{search_name}%'))
    if search_location:
        query = query.filter(Device.location.like(f'%{search_location}%'))
    
    # 分页
    page = request.args.get('page', 1, type=int)
    per_page = 10
    pagination = query.paginate(page=page, per_page=per_page, error_out=False)
    devices = pagination.items
    
    # 获取设备的最新水质数据
    latest_records = {}
    for device in devices:
        latest = WaterQuality.query.filter_by(device_id=device.id).order_by(WaterQuality.timestamp.desc()).first()
        if latest:
            latest_records[device.id] = latest
    
    return render_template('water/index.html', 
                         devices=devices,
                         latest_records=latest_records,
                         pagination=pagination,
                         search_device_id=search_device_id,
                         search_name=search_name,
                         search_location=search_location,
                         title='水质监测')

@water.route('/water/record/<int:device_id>', methods=['GET', 'POST'])
@login_required
def water_record(device_id):
    device = Device.query.get_or_404(device_id)
    
    if request.method == 'POST':
        record = WaterQuality(
            device_id=device_id,
            ph=float(request.form.get('ph')),
            turbidity=float(request.form.get('turbidity')),
            dissolved_oxygen=float(request.form.get('dissolved_oxygen')),
            conductivity=float(request.form.get('conductivity')),
            temperature=float(request.form.get('temperature')),
            timestamp=datetime.now()
        )
        
        db.session.add(record)
        db.session.commit()
        flash('水质数据记录成功', 'success')
        return redirect(url_for('water.water_index'))
    
    return render_template('water/record.html',
                         device=device,
                         title='记录水质数据')

@water.route('/water/history/<int:device_id>')
@login_required
def water_history(device_id):
    device = Device.query.get_or_404(device_id)
    page = request.args.get('page', 1, type=int)
    per_page = 10
    pagination = WaterQuality.query.filter_by(device_id=device_id).order_by(
        WaterQuality.timestamp.desc()
    ).paginate(page=page, per_page=per_page, error_out=False)
    records = pagination.items
    
    return render_template('water/history.html',
                         device=device,
                         records=records,
                         pagination=pagination,
                         title='历史水质数据') 